// 算命业务逻辑服务
// 集成天气信息的算命逻辑

const weatherService = require('./weatherService');

class FortuneService {
    // 计算生肖
    static calculateZodiac(birthYear) {
        const zodiacs = ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'];
        const index = (birthYear - 4) % 12;
        return zodiacs[index];
    }
    
    // 计算星座
    static calculateConstellation(birthMonth, birthDay) {
        const constellations = [
            { name: '水瓶座', start: [1, 20], end: [2, 18] },
            { name: '双鱼座', start: [2, 19], end: [3, 20] },
            { name: '白羊座', start: [3, 21], end: [4, 19] },
            { name: '金牛座', start: [4, 20], end: [5, 20] },
            { name: '双子座', start: [5, 21], end: [6, 21] },
            { name: '巨蟹座', start: [6, 22], end: [7, 22] },
            { name: '狮子座', start: [7, 23], end: [8, 22] },
            { name: '处女座', start: [8, 23], end: [9, 22] },
            { name: '天秤座', start: [9, 23], end: [10, 23] },
            { name: '天蝎座', start: [10, 24], end: [11, 22] },
            { name: '射手座', start: [11, 23], end: [12, 21] },
            { name: '摩羯座', start: [12, 22], end: [1, 19] }
        ];

        for (const constellation of constellations) {
            const [startMonth, startDay] = constellation.start;
            const [endMonth, endDay] = constellation.end;
            
            // 处理跨年的星座（摩羯座）
            if (startMonth > endMonth) {
                if ((birthMonth === startMonth && birthDay >= startDay) || 
                    (birthMonth === endMonth && birthDay <= endDay)) {
                    return constellation.name;
                }
            } else {
                // 普通星座
                if ((birthMonth === startMonth && birthDay >= startDay) || 
                    (birthMonth === endMonth && birthDay <= endDay) ||
                    (birthMonth > startMonth && birthMonth < endMonth)) {
                    return constellation.name;
                }
            }
        }
        
        return '未知星座';
    }
    
    // 生成运势（包含天气信息）
    static async generateFortune(zodiac, constellation, name, city = null) {
        const fortuneTemplates = [
            `今日${zodiac}座的你运势不错，${constellation}的特质让你在人际关系中表现出色。`,
            `${constellation}的你今天适合做重要决定，${zodiac}的智慧将指引你前进。`,
            `今日运势平稳，${zodiac}座的坚持和${constellation}的直觉将帮助你克服困难。`,
            `${constellation}的魅力今日格外突出，${zodiac}的幸运将伴随你一整天。`,
            `今天是${zodiac}座的幸运日，${constellation}的能量让你充满活力和创造力。`
        ];
        
        const colors = ['红色', '蓝色', '绿色', '黄色', '紫色', '橙色', '粉色', '金色'];
        
        // 基于姓名和日期生成种子
        const seed = this.generateSeed(name, zodiac, constellation);
        
        // 生成运势文本
        const fortuneIndex = seed % fortuneTemplates.length;
        let todayFortune = fortuneTemplates[fortuneIndex];
        
        // 尝试获取天气信息并融入运势
        let weatherInfo = null;
        try {
            if (weatherService.checkWeatherConfig()) {
                if (city) {
                    weatherInfo = await weatherService.getWeatherByCity(city);
                } else {
                    weatherInfo = await weatherService.getCurrentWeather();
                }
                
                if (weatherInfo && weatherInfo.success) {
                    todayFortune = this.enhanceFortuneWithWeather(todayFortune, weatherInfo.data, zodiac, constellation);
                }
            }
        } catch (error) {
            console.log('获取天气信息失败，使用基础运势:', error.message);
            // 天气获取失败不影响基础运势生成
        }
        
        // 生成幸运数字 (1-99)
        const luckyNumber = (seed % 99) + 1;
        
        // 生成幸运颜色
        const colorIndex = (seed * 7) % colors.length;
        const luckyColor = colors[colorIndex];
        
        return {
            today: todayFortune,
            luckyNumber: luckyNumber,
            luckyColor: luckyColor,
            weather: weatherInfo ? weatherInfo.data : null
        };
    }
    
    // 根据天气信息增强运势描述
    static enhanceFortuneWithWeather(baseFortune, weather, zodiac, constellation) {
        const weatherEnhancements = {
            '晴': `今日${weather.city}天气晴朗，正如你的运势一样明朗。`,
            '多云': `今日${weather.city}多云的天气提醒你保持灵活性，机会在云层后等待。`,
            '阴': `今日${weather.city}阴天，适合内省和思考，${constellation}的智慧将指引方向。`,
            '雨': `今日${weather.city}有雨，雨水洗涤尘埃，也将为你带来新的开始。`,
            '雪': `今日${weather.city}飘雪，纯洁的雪花象征着新的机遇即将到来。`,
            '雾': `今日${weather.city}有雾，虽然视线模糊，但${zodiac}的直觉会指引正确方向。`
        };
        
        // 根据天气情况添加相应的运势描述
        let weatherAdvice = '';
        for (const [weatherType, advice] of Object.entries(weatherEnhancements)) {
            if (weather.weather.includes(weatherType)) {
                weatherAdvice = advice;
                break;
            }
        }
        
        // 根据温度给出建议
        const temp = parseInt(weather.temperature);
        let tempAdvice = '';
        if (temp < 10) {
            tempAdvice = '今日气温较低，注意保暖，温暖的心情会带来好运。';
        } else if (temp > 30) {
            tempAdvice = '今日气温较高，保持清爽心境，热情将为你带来机遇。';
        } else {
            tempAdvice = '今日气温适宜，正是行动的好时机。';
        }
        
        // 组合运势信息
        return `${baseFortune} ${weatherAdvice} ${tempAdvice}`;
    }
    
    // 生成种子数字用于随机化
    static generateSeed(name, zodiac, constellation) {
        const today = new Date();
        const dateString = today.getFullYear() + '' + (today.getMonth() + 1) + '' + today.getDate();
        
        // 简单的字符串哈希算法
        let hash = 0;
        const input = name + zodiac + constellation + dateString;
        
        for (let i = 0; i < input.length; i++) {
            const char = input.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // 转换为32位整数
        }
        
        return Math.abs(hash);
    }
}

module.exports = FortuneService;